package com.blueocean_health.care.management.controller;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.blueocean_health.care.management.common.LocalManager;
import com.blueocean_health.care.management.common.base.em.TimeType;
import com.blueocean_health.care.management.common.base.time.TimeUtils;
import com.blueocean_health.care.management.common.excel.ExcelUtil;
import com.blueocean_health.care.management.domain.base.SysResult;
import com.blueocean_health.care.management.domain.base.SysResultByPage;
import com.blueocean_health.care.management.domain.base.User;
import com.blueocean_health.care.management.domain.dto.AppointmentOrderSelectInfoEntity;
import com.blueocean_health.care.management.domain.dto.CashRecordTableDto;
import com.blueocean_health.care.management.domain.dto.OrderInfoDto;
import com.blueocean_health.care.management.domain.dto.OrderSelectInfoEntity;
import com.blueocean_health.care.management.domain.dto.OrderSelectInfoReceivableEntity;
import com.blueocean_health.care.management.domain.dto.OrderSelectInfoToChargeEntity;
import com.blueocean_health.care.management.domain.dto.RelationListDto;
import com.blueocean_health.care.management.domain.ordervo.SelectOrderVo;
import com.blueocean_health.care.management.domain.ordervo.ToChargeVo;
import com.blueocean_health.care.management.em.LocalManagerType;
import com.blueocean_health.care.management.em.OrderUpdateFlagEnum;
import com.blueocean_health.care.management.exception.OrderException;
import com.blueocean_health.care.management.service.IChareOrderService;
import com.blueocean_health.care.management.service.IOrderSelectService;
import com.github.pagehelper.PageInfo;


@RestController
@RequestMapping(value = "web/order")
public class SelectOrderHandler{
	@Resource
	private IOrderSelectService iOrderSelectService;
	@Resource
	private IChareOrderService iChareOrderService;
	@RequestMapping(value = "list")
	//查询订单列表
	public SysResult selectOrderList(@RequestBody(required = false) SelectOrderVo order){
		User user = LocalManager.getVal(LocalManagerType.USER_WEB);
		order.setHospitalId(user.getHospitalId());
		//正常订单已编辑过
		//order.setOrderUpdateFlag(OrderUpdateFlagEnum._1.getKey());
		Map<String, Object> selectOrderList = iOrderSelectService.selectOrderList(order);
		
		return SysResult.ok(selectOrderList);
		
	}
	@RequestMapping(value = "checkhaverefund")
	//查询是否有退款单
	public  SysResult checkHaveRefund(@RequestBody Map<String, String> orderId){
		
		Map<String, Boolean> checkHaveRefund = iOrderSelectService.checkHaveRefund(orderId.get("orderId"));
		return SysResult.ok(checkHaveRefund);
		
	}
	@RequestMapping(value = "appointmentlist")
	//查询预约订单列表
	public SysResult selectOrderAppointmentList(@RequestBody(required = false) SelectOrderVo order){
		User user = LocalManager.getVal(LocalManagerType.USER_WEB);
		order.setHospitalId(user.getHospitalId());
		//预约单包括未编辑过和为编辑过已读
		String[] orderUpdateFlags={OrderUpdateFlagEnum._0.getKey(),OrderUpdateFlagEnum._2.getKey()};
		order.setOrderUpdateFlags(orderUpdateFlags);
	 Map<String, Object> appointmentSelectOrderList = iOrderSelectService.appointmentSelectOrderList(order);
		
		return SysResultByPage.ok(appointmentSelectOrderList.get("list"),appointmentSelectOrderList.get("pagetotal"));
		
	}
	@RequestMapping(value = "selectunreadorder")
	//查询预约数量
	public SysResult selectunreadorder(){
		User user = LocalManager.getVal(LocalManagerType.USER_WEB);
		int selectUnreadOrder = iOrderSelectService.selectUnreadOrder(user.getHospitalId());
		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put("count", selectUnreadOrder);
		return SysResult.ok(map);
		
	}
	@RequestMapping(value = "appointmentlistExcel")
	//导出预约订单列表
		public void appointmentlistExcel(SelectOrderVo order,HttpServletResponse response){
			try {
			User user = LocalManager.getVal(LocalManagerType.USER_WEB);
			order.setHospitalId(user.getHospitalId());
			String[] orderUpdateFlags={OrderUpdateFlagEnum._0.getKey(),OrderUpdateFlagEnum._2.getKey()};
			order.setOrderUpdateFlags(orderUpdateFlags);
			//PageInfo<OrderSelectInfoEntity> selectOrderList = iOrderSelectService.selectOrderList(order);
			 Map<String, Object> appointmentSelectOrderList = iOrderSelectService.appointmentSelectOrderList(order);
			 List<AppointmentOrderSelectInfoEntity> list = (List<AppointmentOrderSelectInfoEntity>)appointmentSelectOrderList.get("list");
				String finalFileName = URLEncoder.encode("预约单"+TimeUtils.getTime(TimeType.yyyyMMddHHmmssSSS)+".xls", "UTF8");
				//response.addHeader("Content-Disposition", "attachment;filename=" + finalFileName);
				response.setContentType("application/force-download");
				response.addHeader("Content-Disposition", "attachment;filename=" + finalFileName);
				OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
				ExcelUtil.getInstance().exportObj2Excel(toClient, list, AppointmentOrderSelectInfoEntity.class);
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
	@RequestMapping(value = "relationList")
	//查询关联订单列表
	public SysResult relationList(@RequestBody(required = false) SelectOrderVo order){
		User user = LocalManager.getVal(LocalManagerType.USER_WEB);
		order.setHospitalId(user.getHospitalId());
		List<RelationListDto> relationList = iOrderSelectService.relationList(order);
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("list", relationList);
		return SysResult.ok(map);
		
	}
	@RequestMapping(value = "listExcel")
	//查询订单列表
		public void selectOrderListExcel(SelectOrderVo order,HttpServletResponse response){
			try {
//			SelectOrderVo order=new SelectOrderVo();
			User user = LocalManager.getVal(LocalManagerType.USER_WEB);
			order.setHospitalId(user.getHospitalId());
//			order.setOrderUpdateFlag(OrderUpdateFlagEnum._1.getKey());
			Map<String, Object> selectOrderList = iOrderSelectService.selectOrderList(order);
			List<OrderSelectInfoEntity> list = (List<OrderSelectInfoEntity>)selectOrderList.get("list");
				String finalFileName = URLEncoder.encode("订单列表"+TimeUtils.getTime(TimeType.yyyyMMddHHmmssSSS)+".xls", "UTF8");
				//response.addHeader("Content-Disposition", "attachment;filename=" + finalFileName);
				response.setContentType("application/force-download");
				response.addHeader("Content-Disposition", "attachment;filename=" + finalFileName);
				OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
				ExcelUtil.getInstance().exportObj2Excel(toClient, list, OrderSelectInfoEntity.class);
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
	//查询订单详情
	@RequestMapping(value = "query")
	public SysResult selectOrderInfo(@RequestBody SelectOrderVo order){
		if(order==null){
			return SysResult.error("参数不能为空");
		}
		User user = LocalManager.getVal(LocalManagerType.USER_WEB);
		order.setHospitalId(user.getHospitalId());
		OrderInfoDto selectOrderInfo = iOrderSelectService.selectOrderInfo(order);
		
		return SysResult.ok(selectOrderInfo);
		
	}
	//查询应收
	@RequestMapping(value = "selectOrdertotalAmount")
	public SysResult selectOrdertotalAmount(@RequestBody SelectOrderVo order){
		if(order==null){
			return SysResult.error("参数不能为空");
		}
		//Double selectOrdertotalAmount = iOrderSelectService.selectOrdertotalAmount(order.getOrderId());
		Double selectOrdertotalAmount = iChareOrderService.selectReceivableAmount(order.getOrderId());
		Map<String, Double> map=new HashMap<String, Double>();
		map.put("receivableAmount", selectOrdertotalAmount);
		return SysResult.ok(map);
	}
	//导出待收款列表
	@RequestMapping(value = "receivableListExcel")
	public void selectReceivableListExcel(ToChargeVo order,HttpServletResponse response){
		try {
//		ToChargeVo order=new ToChargeVo();
		User user = LocalManager.getVal(LocalManagerType.USER_WEB);
		order.setHospitalId(user.getHospitalId());
//		order.setMinReceivableAmount(request.getParameter("minReceivableAmount"));
//		order.setMaxReceivableAmount(request.getParameter("maxReceivableAmount"));
//		order.setDepartment(request.getParameter("department"));
//		order.setPatientName(request.getParameter("patientName"));
//		order.setPhone(request.getParameter("phone"));
//		order.setWorkerNames(request.getParameter("workerNames"));
//		order.setServiceType(request.getParameter("serviceType"));
//		order.setSort(request.getParameter("sort"));
//		order.setOrderType(request.getParameter("orderType"));
		Map<String, Object> selectReceivableList = iOrderSelectService.selectReceivableList(order);
		List<OrderSelectInfoReceivableEntity> list=(List<OrderSelectInfoReceivableEntity>)selectReceivableList.get("list");
		String finalFileName = URLEncoder.encode("收费提醒"+TimeUtils.getTime(TimeType.yyyyMMddHHmmssSSS)+".xls", "UTF8");
		response.setContentType("application/force-download");
		response.setHeader("Content-Disposition", "attachment;filename=" + finalFileName);
		OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
		ExcelUtil.getInstance().exportObj2Excel(toClient, list, OrderSelectInfoReceivableEntity.class);
		} catch ( IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//查询待收款列表
		@RequestMapping(value = "receivableList")
		public SysResult selectReceivableList(@RequestBody ToChargeVo order){
			User user = LocalManager.getVal(LocalManagerType.USER_WEB);
			order.setHospitalId(user.getHospitalId());
			Map<String, Object> selectReceivableList = iOrderSelectService.selectReceivableList(order);
			List<OrderSelectInfoReceivableEntity> list = (List<OrderSelectInfoReceivableEntity>)selectReceivableList.get("list");
			long total = (Long)selectReceivableList.get("total");
			return SysResultByPage.ok(list,total);
		}
		//导出待续费列表
		@RequestMapping(value = "toChargeListExcel")
		public void toChargeList(ToChargeVo order,HttpServletResponse response){
			try {
			User user = LocalManager.getVal(LocalManagerType.USER_WEB);
			order.setHospitalId(user.getHospitalId());
			Map<String, Object> selectOrderList = iOrderSelectService.toChargeList(order);
			List<OrderSelectInfoToChargeEntity> list = (List<OrderSelectInfoToChargeEntity>)selectOrderList.get("list");
			String finalFileName = URLEncoder.encode("续费提醒"+TimeUtils.getTime(TimeType.yyyyMMddHHmmssSSS)+".xls", "UTF8");
			response.addHeader("Content-Disposition", "attachment;filename=" + finalFileName);
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			ExcelUtil.getInstance().exportObj2Excel(toClient, list, OrderSelectInfoToChargeEntity.class);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	//查询待续费列表
		@RequestMapping(value = "toChargeList")
		public SysResult toChargeList(@RequestBody ToChargeVo order){
			User user = LocalManager.getVal(LocalManagerType.USER_WEB);
			order.setHospitalId(user.getHospitalId());
			Map<String, Object> selectOrderList = iOrderSelectService.toChargeList(order);
			List<OrderSelectInfoToChargeEntity> list = (List<OrderSelectInfoToChargeEntity>)selectOrderList.get("list");
			long total = (Long)selectOrderList.get("total");
//			if(total<0){
//				return SysResult.error("你输入的条件不正确");
//			}
			return SysResultByPage.ok(list, total);
		}
		
		 //取消续费
		  @RequestMapping("/cancelrenewal")
		    public SysResult cancelrenewal(@RequestBody SelectOrderVo order) throws OrderException {
			   Boolean updateOrderCreateUser = iOrderSelectService.cancelrenewal(order.getOrderId());
			   if(updateOrderCreateUser){
				 return  SysResult.ok();
			   }else {
				   return SysResult.error("该订单已被接单");
			   
			   }
			   }	

}
